package com.gwi.springboot;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * base64  .wav加解密
 * @author wangfei
 * @date 2021-10-13 19:22
 */
public class AudioPlayerUtils {

    /**
     * 将音频wav解析成base64位数据
     * @param path
     * @return
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);;
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }

    /**
     * base64转换音频wav
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath)throws Exception {


        InputStream inputStream = new FileInputStream(new File("D:/2.txt"));
//        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        byte[] buffer = new BASE64Decoder().decodeBuffer(inputStream);
        FileOutputStream out = new FileOutputStream(targetPath+"/1.wav");
        out.write(buffer);
        out.close();
    }

    /**
     * base64保存txt文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void toFile(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

    public static void main(String[] args) {
        try {
//            String str = AudioPlayerUtils.encodeBase64File("D:/temp111.wav");

//            toFile(str, "D:/2.txt");

            //将base64字符解码保存文件
//            decoderBase64File(str, "D:/");

            decoderBase64File("", "D:/");

        } catch (Exception e) {
        }

    }
}
